package org.jianfa.homework.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        //1. 获取验证码
        //2. 注册
        //3. 登录
        if (path.equals("/code/create")
            || path.equals("/user/register")
            || path.equals("/user/login")) {
            return chain.filter(exchange);
        }

        MultiValueMap<String, HttpCookie>  cookieMultiValueMap = request.getCookies();
        HttpCookie httpCookie = cookieMultiValueMap.getFirst("Token");
        String token = "";
        if (httpCookie != null) {
            token = httpCookie.getValue();
        }

        //如果token为空，直接返回
        if (StringUtils.isEmpty(token)) {

        }

        //1. 根据token获取邮箱
        //2. 登出
        return chain.filter(exchange);
    }

    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 3;
    }
}
